import Vue from 'vue'
import VueRouter from 'vue-router'
import { getToken } from '@/utils/storage'
Vue.use(VueRouter)

const whiteList = [ '/login' ]

const routes = [
	{
		path: '/login',
		name: 'login',
		component: () => import('../views/login/index.vue')
		// /* webpackChunkName: "about" */  魔法注释
		/* 文件分类打包 */
	},
	{
		path: '/',
		name: 'layout',
		redirect: '/dashboard',
		component: () => import('../views/layout/index.vue'),
		children: [
			{
				path: '/dashboard',
				name: 'dashboard',
				component: () => import('../views/dashboard/index.vue')
			},
			{
				path: '/article',
				name: 'article',
				component: () => import('../views/article/index.vue')
			}
		]
	}
	// {
	//   path: '/about',
	//   name: 'About',
	//   component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
	// }
]

const router = new VueRouter({
	routes
})

/* 路由导航守卫 */
router.beforeEach((to, from, next) => {
	/*
  1-获取token
  2、根据token判断
    有token
      表示已经登录了，可以直接访问，需要放行 next
    无token
      判断是不是有的页面没有token也可以访问  比如 /login  【白名单】  是可以直接访问的
      判断没有token又不能直接去访问的【不是白名单的】  跳转到登录页面
  
  */
	const token = getToken()
	if (token) {
		next()
	} else {
		if (whiteList.includes(to.path)) {
			next()
		} else {
			next('/login')
		}
	}
})

//保存原型对象的Push
let originPush = VueRouter.prototype.push
let originReplace = VueRouter.prototype.replace
//重写push方法
VueRouter.prototype.push = function(location, res, rej) {
	if (res && rej) {
		originPush.call(this, location, res, rej)
	} else {
		originPush.call(this, location, () => {}, () => {})
	}
}
//重写replace方法
VueRouter.prototype.replace = function(location, res, rej) {
	if (res && rej) {
		originReplace.call(this, location, res, rej)
	} else {
		originReplace.call(this, location, () => {}, () => {})
	}
}

export default router
